<?php

namespace App\Providers;

use App\Models\Open\MicroApp;
use App\Models\Open\SysAccount;
use Illuminate\Support\ServiceProvider;

class WechatServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     */
    public function register(): void
    {
        $this->app->singleton('microApp', function($app, $params) {
            $access_token = request()->get('access_token');
            if($access_token) {
                $microApp = MicroApp::with(['sysAccount.appType'])->where('access_token', $access_token)->where('expire_time', '>', new DateTime())->first();
            } else {
                $appid = @$params['appid'];
                $appsecret = @$params['appsecret'];
                if($appid && $appsecret) {
                    $microApp = MicroApp::with(['sysAccount.appType'])->where(['appid'=>$appid])->where(['appsecret'=>$appsecret])->first();
                } else {
                    $microAppAlias = @$params['aliasname'] ?: env('WECHAT_ALIASNAME', 'offiaccount');
                    $microApp = MicroApp::with(['sysAccount.appType'])->where(['aliasname'=>$microAppAlias])->first();
                }
            }
            return $microApp;
        });

        $this->app->singleton('wechatApp', function($app, $params) {
            $microAppAlias = @$params['aliasname'];
            if($microAppAlias) {
                $microApp = resolve('microApp', ['aliasname'=>$microAppAlias]);
                $sysAccount = $microApp->sysAccount;
            } else {
                $sysId = @$params['sysId'];
                if($sysId) {
                    $sysAccount = SysAccount::find($sysId);
                } else {
                    $microApp = resolve('microApp');
                    $sysAccount = $microApp->sysAccount;
                }
            }
            if ($sysAccount->appType->aliasname == 'miniprogram') {
                $config = [
                    'app_id' => $sysAccount['appid'],
                    'secret' => $sysAccount['appsecret'],
                ];
                return new \EasyWeChat\MiniApp\Application($config);
            } else {
                $config = [
                    'app_id' => $sysAccount['appid'],
                    'secret' => $sysAccount['appsecret'],
                    'token' => $sysAccount['token'],
                    'aes_key' => $sysAccount['aes_key'],
                ];
                return new \EasyWeChat\OfficialAccount\Application($config);
            }
        });
    }

    /**
     * Bootstrap services.
     */
    public function boot(): void
    {
        //
    }
}
